<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="p-2">
    <!-- <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave"> -->
      <div class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" size="small" :model="queryParams" :inline="true" label-width="120px">
            <el-form-item label="算法名称" prop="algorithmName">
              <el-input v-model="queryParams.algorithmName" placeholder="请输入算法名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="实现语言" prop="algorithmLanguage">
              <el-select v-model="queryParams.algorithmLanguage" placeholder="请选择实现语言">
                <el-option v-for="item in languageList" :label="item.name" :value="item.val" :key="item.val"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否默认算法" prop="isDefault">
              <el-select v-model="queryParams.isDefault" placeholder="请选择是否默认算法">
                <el-option label="默认" :value="0"></el-option>
                <el-option label="item.name" :value="1"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    <!-- </transition> -->

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button plain icon="Download" @click="handleDownload()">导出</el-button>
          </el-col> -->
        </el-row>
      </template>

      <el-table ref="tableRef" v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
        <el-table-column label="算法名称" prop="algorithmName" />
        <el-table-column label="算法业务类型" prop="algorithmType" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ typeMap[scope.row.algorithmType] }}
          </template>
        </el-table-column>
        <el-table-column label="实现语言" prop="algorithmLanguage" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.algorithmLanguage }}
          </template>
        </el-table-column>
        <el-table-column label="算法描述" prop="description">
          <template #default="scope">
            {{ scope.row.description }}
          </template>
        </el-table-column>
        <el-table-column label="是否默认算法" prop="isDefault">
          <template #default="scope">   
            {{ scope.row.isDefault == '1' ? '手动新增' : '默认' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column fixed="right" label="操作" width="190">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button size="small" link type="primary" icon="View" @click="handleView(scope.row)">详情</el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
              <el-button size="small" link type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="small" link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagenation" style="display: flex; justify-content: end; padding-top: 10px;">
        <el-pagination
          v-show="total > 0"
          layout="prev, pager, next,jumper"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          v-model:current-page="queryParams.pageNum"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <AlgotithmOperate v-if="dialogVisible" :languageList="languageList" :pageType="pageType" :row="rowData" :dialogVisible="dialogVisible" @handleEvent="handleEvent" />
    <!-- <TemplateDetail v-if="viewVisible" :row="rowData" :viewVisible="viewVisible" @handleEvent="handleEvent"  /> -->
  </div>
</template>

<script setup name="AlgorithmConfig">
import AlgotithmOperate from './AlgotithmOperate.vue';
// import TemplateDetail from './TemplateDetail.vue';
import { downloadFile } from '@/utils/index';
import { 
  getAlgorithmConfigList, 
  deleteAlgorithmConfig,
  exportAlgorithmConfig
} from '@/api/algorithmConfig/index';
const queryFormRef = ref();
const loading = ref(true);
const dialogVisible = ref(false);
const pageType = ref('');
const total = ref(0);
const rowData = ref({});
const selectionList = ref([]);
const selectionListAll = ref([]);
const tableList = ref([]);
const tableRef = ref(null);
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    algorithmName: '',
    algorithmLanguage: '',
    isDefault: ''
});
const languageList = [
  {val: 'Python', name: 'Python'},
  {val: 'Javascript', name: 'Javascript'},
  // {id: 3, name: 'C++'}, 
]
const typeMap = {
  'section': '型材算法'
}
const handleEvent = (prop) => {
  if (prop.type == 'success') {
    getList();
  }
  dialogVisible.value = false;
}
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val;
  getList();
};  
/**
 * 查询角色列表
 */
const getList = () => {
  loading.value = true;
  getAlgorithmConfigList(queryParams.value).then((res) => {
    tableList.value = res.rows;
    total.value = res.total
    loading.value = false;
    nextTick(() => {
      setSelectRow();
    })
  }).finally(() => {
    loading.value = false; 
  })
};
const handleView = (row) => {
  rowData.value = row;
  pageType.value = 'VIEW';
  dialogVisible.value = true;
}
const handleAdd = () => { 
  rowData.value = null;
  pageType.value = 'ADD';
  dialogVisible.value = true;
}
const handleEdit = (row) => {
  if (row.isDefault == '0') {
    ElMessage({ showClose: true, message: '默认算法不能编辑。', type: 'error' });
    return;
  }
  rowData.value = row;
  pageType.value = 'EDIT';
  dialogVisible.value = true;
}
const handleDownload = () => {
  exportAlgorithmConfig({
    algorithmName: queryParams.value.algorithmName,
    algorithmLanguage: queryParams.value.algorithmLanguage,
    isDefault: queryParams.value.isDefault,
  }).then((res) => {
    if (res?.code === 500) {
      ElMessage({ showClose: true, message: '下载失败。', type: 'error' });
      return;
    }
    downloadFile(res, `算法配置列表`, 'xlsx');
  });
}
const handleSelectionChange = (val) => {
  // 表格选项发生变化
  selectionList.value = val
  nextTick(() => {
    changePageCoreRecordData()
  })
}
// 记忆选择核心方法
const changePageCoreRecordData = () => {
  // 标识当前行的唯一键的名称
  const idKey = 'id';
  // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
  if (selectionListAll.value.length <= 0) {
    selectionListAll.value = selectionList.value;
    return
  }
  // 总选择里面的key集合
  const selectAllIds = []
  selectionListAll.value.forEach(row => {
    selectAllIds.push(row[idKey])
  })
  const selectIds = []
  // 获取当前页选中的id
  selectionList.value.forEach(row => {
    selectIds.push(row[idKey])
    // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
    if (selectAllIds.indexOf(row[idKey]) < 0) {
      selectionListAll.value.push(row)
    }
  })
  const noSelectIds = []
  // 得到当前页没有选中的id
  tableList.value.forEach(row => {
    if (selectIds.indexOf(row[idKey]) < 0) {
      noSelectIds.push(row[idKey])
    }
  })
  noSelectIds.forEach(id => {
    if (selectAllIds.indexOf(id) >= 0) {
      for (let i = 0; i < selectionListAll.value.length; i++) {
        if (selectionListAll.value[i][idKey] == id) {
          // 如果总选择中有未被选中的，那么就删除这条
          selectionListAll.value.splice(i, 1)
          break
        }
      }
    }
  })
}
// 设置选中的方法
const setSelectRow = () => {
  if (!selectionListAll.value || selectionListAll.value.length <= 0) {
    return
  }
  // 标识当前行的唯一键的名称
  const idKey = 'id';
  const selectAllIds = []
  selectionListAll.value.forEach(row => {
    selectAllIds.push(row[idKey])
  })
  tableRef.value.clearSelection()
  for (var i = 0; i < tableList.value.length; i++) {
    if (selectAllIds.indexOf(tableList.value[i][idKey]) >= 0) {
      // 设置选中，记住table组件需要使用ref="table"
      tableRef.value.toggleRowSelection(tableList.value[i], true)
    }
  }
}
/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};
/**删除按钮操作 */
const handleDelete = async (row) => {
  if (row.isdefault == '1') {
    ElMessage.error('默认算法无法删除');
    return; 
  }
  // const ids = row?.id ? [row.id] : selectionListAll.value.map((el) => el.id);
  ElMessageBox.confirm(`是否确认删除算法i【${row.algorithmName}】？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteAlgorithmConfig([row.id]);
    ElMessage.success('删除成功');
    getList();
  }).catch(() => {
    ElMessage.error('删除失败');
  });
};

onMounted(() => {
  getList();
});
</script>

